#include "Queue.h"

void QueueInit(Queue* q)
{
	assert(q);
	q->fornt = NULL;
	q->rear = NULL;
	q->size = 0;
}

void QueuePush(Queue* q, QDatatype x)
{
	assert(q);

	Qlistnode* newnode = (Qlistnode*)malloc(sizeof(Qlistnode));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	if (q->rear == NULL)
	{
		q->fornt = q->rear = newnode;
	}
	else
	{
		q->rear->next = newnode;
		q->rear = newnode;
	}
	q->size++;
}

void QueuePop(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));

	if (q->fornt == q->rear)
	{
		free(q->fornt);
		q->fornt = NULL;
		q->rear = NULL;
	}
	else
	{
		Qlistnode* newnode = q->fornt->next;
		free(q->fornt);
		q->fornt = newnode;
	}
	q->size--;
}

bool QueueEmpty(Queue* q)
{
	assert(q);

	return q->fornt ==  NULL;
}

QDatatype QueueFornt(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));

	return q->fornt->data;
}

QDatatype QueueRear(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));

	return q->rear->data;
}

void QueueDestroy(Queue* q)
{
	assert(q);

	Qlistnode* newnode = q->fornt;
	while (newnode)
	{
		q->fornt = newnode->next;
		free(newnode);
		newnode = q->fornt;
	}
	q->fornt = q->rear = NULL;
	q->size = 0;
}

int QueueSize(Queue* q)
{
	assert(q);
	
	return q->size;
}